#include "AMUrlSchemeHandler.h"
#include <QJsonObject>
#include <QBuffer>

AMUrlSchemeHandler::AMUrlSchemeHandler(QObject *parent)
    : QWebEngineUrlSchemeHandler(parent)
{
}

AMUrlSchemeHandler::~AMUrlSchemeHandler()
{
}

void AMUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob* pReqJob)
{
    QJsonObject jsonObj;
    jsonObj.insert("requestUrl", pReqJob->requestUrl().toString());
    jsonObj.insert("requestMethod", QString(pReqJob->requestMethod()));
    jsonObj.insert("initiator", pReqJob->initiator().toString());

    //if (pReqJob->requestUrl().toString().startsWith("amurl://www.baidu.com"))
    {
        if (pReqJob->requestMethod() == "GET")
        {
            jsonObj.insert("result", "GET 0");
        }
        else if (pReqJob->requestMethod() == "POST")
        {
            jsonObj.insert("result", "POST 1");
        }
        else
        {
            pReqJob->fail(QWebEngineUrlRequestJob::RequestDenied);
            return;
        }
    }


    QBuffer* buffer = new QBuffer;
    connect(pReqJob, SIGNAL(destroyed()), buffer, SLOT(deleteLater()));
    buffer->open(QIODevice::WriteOnly);
    QString strJson = QJsonDocument(jsonObj).toJson(QJsonDocument::Indented);
    buffer->write(strJson.toUtf8());
    buffer->close();

    pReqJob->reply("application/json", buffer);
}
